"""
邮件系统使用示例
演示如何使用邮件服务发送各种类型的邮件
"""

import asyncio
from datetime import datetime
from sqlalchemy.orm import Session

from app.core.database import SessionLocal
from app.services.email_service import EmailService
from app.schemas.email import (
    EmailSendRequest, EmailTemplateRequest, UserMessageRequest,
    EmailBatchRequest, EmailPriorityEnum
)
from app.models.user import User


async def example_send_simple_email():
    """示例：发送简单邮件"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 创建邮件请求
        request = EmailSendRequest(
            recipient_email="test@example.com",
            recipient_name="测试用户",
            subject="FastAPI Platform 测试邮件",
            body_html="""
            <h2>测试邮件</h2>
            <p>这是一封来自 FastAPI Platform 的测试邮件。</p>
            <p>发送时间：{}</p>
            """.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
            priority=EmailPriorityEnum.NORMAL
        )
        
        # 发送邮件（系统邮件，无发送者）
        email_message = await email_service.send_email(request)
        print(f"✅ 简单邮件发送成功，邮件ID: {email_message.id}")
        
    except Exception as e:
        print(f"❌ 发送简单邮件失败: {e}")
    finally:
        db.close()


async def example_send_welcome_email():
    """示例：发送欢迎邮件"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 模拟新用户数据
        template_data = {
            "user_name": "张三",
            "user_email": "zhangsan@example.com",
            "user_id": "12345",
            "platform_name": "FastAPI Platform",
            "platform_url": "http://localhost:8989",
            "registration_date": datetime.now().strftime("%Y年%m月%d日"),
            "help_url": "http://localhost:8989/help"
        }
        
        # 创建模板邮件请求
        request = EmailTemplateRequest(
            recipient_email="zhangsan@example.com",
            recipient_name="张三",
            template_name="welcome",
            template_data=template_data,
            priority=EmailPriorityEnum.HIGH
        )
        
        # 发送欢迎邮件
        email_message = await email_service.send_template_email(request)
        print(f"✅ 欢迎邮件发送成功，邮件ID: {email_message.id}")
        
    except Exception as e:
        print(f"❌ 发送欢迎邮件失败: {e}")
    finally:
        db.close()


async def example_send_user_message():
    """示例：发送用户间消息"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 获取发送者和接收者用户（这里需要实际的用户数据）
        sender = db.query(User).filter(User.email == "sender@example.com").first()
        recipient = db.query(User).filter(User.email == "recipient@example.com").first()
        
        if not sender or not recipient:
            print("❌ 需要先创建测试用户")
            return
        
        # 创建用户消息请求
        request = UserMessageRequest(
            recipient_id=recipient.id,
            subject="项目合作邀请",
            message="""
            你好！
            
            我是张三，看到你在平台上的项目很有意思，想邀请你一起合作开发一个新项目。
            
            项目详情：
            - 基于AI的数据分析平台
            - 预计开发周期3个月
            - 技术栈：Python, FastAPI, React
            
            如果你有兴趣，请回复这条消息，我们可以进一步讨论。
            
            期待你的回复！
            
            张三
            """,
            priority=EmailPriorityEnum.NORMAL
        )
        
        # 发送用户消息
        email_message = await email_service.send_user_message(request, sender)
        print(f"✅ 用户消息发送成功，邮件ID: {email_message.id}")
        
    except Exception as e:
        print(f"❌ 发送用户消息失败: {e}")
    finally:
        db.close()


async def example_send_notification():
    """示例：发送系统通知"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 系统通知数据
        template_data = {
            "user_name": "李四",
            "notification_title": "系统维护通知",
            "notification_message": "系统将于今晚23:00-01:00进行维护升级，期间服务可能暂时不可用。",
            "notification_type": "warning",
            "notification_time": datetime.now().strftime("%Y年%m月%d日 %H:%M"),
            "platform_name": "FastAPI Platform",
            "platform_url": "http://localhost:8989",
            "action_url": "http://localhost:8989/maintenance",
            "action_text": "查看维护详情",
            "details": {
                "维护时间": "2024年1月15日 23:00-01:00",
                "影响范围": "全部服务",
                "预计恢复": "2024年1月16日 01:00"
            },
            "additional_info": [
                "维护期间请保存好您的工作",
                "维护完成后系统性能将得到提升",
                "如有紧急问题请联系客服热线"
            ],
            "help_url": "http://localhost:8989/help"
        }
        
        # 创建通知邮件请求
        request = EmailTemplateRequest(
            recipient_email="lisi@example.com",
            recipient_name="李四",
            template_name="notification",
            template_data=template_data,
            priority=EmailPriorityEnum.HIGH
        )
        
        # 发送通知邮件
        email_message = await email_service.send_template_email(request)
        print(f"✅ 系统通知发送成功，邮件ID: {email_message.id}")
        
    except Exception as e:
        print(f"❌ 发送系统通知失败: {e}")
    finally:
        db.close()


async def example_send_batch_emails():
    """示例：批量发送邮件"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 收件人列表
        recipients = [
            {"email": "user1@example.com", "name": "用户1"},
            {"email": "user2@example.com", "name": "用户2"},
            {"email": "user3@example.com", "name": "用户3"},
        ]
        
        # 创建批量邮件请求
        request = EmailBatchRequest(
            recipients=recipients,
            subject="FastAPI Platform 功能更新通知",
            body_html="""
            <h2>平台功能更新</h2>
            <p>亲爱的用户，</p>
            <p>我们很高兴地宣布，FastAPI Platform 新增了以下功能：</p>
            <ul>
                <li>📧 邮件系统 - 支持用户间消息发送</li>
                <li>🔔 实时通知 - 重要事件及时提醒</li>
                <li>📊 数据分析 - 更强大的数据处理能力</li>
            </ul>
            <p>立即登录体验新功能！</p>
            """,
            priority=EmailPriorityEnum.NORMAL
        )
        
        # 批量发送邮件
        batch_id, email_messages = await email_service.send_batch_emails(request)
        print(f"✅ 批量邮件发送成功，批次ID: {batch_id}，邮件数量: {len(email_messages)}")
        
    except Exception as e:
        print(f"❌ 批量发送邮件失败: {e}")
    finally:
        db.close()


async def example_send_password_reset():
    """示例：发送密码重置邮件"""
    db = SessionLocal()
    try:
        email_service = EmailService(db)
        
        # 密码重置数据
        template_data = {
            "user_name": "王五",
            "user_email": "wangwu@example.com",
            "reset_code": "ABC123",
            "reset_url": "http://localhost:8989/reset-password?token=abc123def456",
            "request_time": datetime.now().strftime("%Y年%m月%d日 %H:%M:%S"),
            "request_ip": "192.168.1.100",
            "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "expiry_hours": 24,
            "platform_name": "FastAPI Platform",
            "help_url": "http://localhost:8989/help"
        }
        
        # 创建密码重置邮件请求
        request = EmailTemplateRequest(
            recipient_email="wangwu@example.com",
            recipient_name="王五",
            template_name="password_reset",
            template_data=template_data,
            priority=EmailPriorityEnum.URGENT
        )
        
        # 发送密码重置邮件
        email_message = await email_service.send_template_email(request)
        print(f"✅ 密码重置邮件发送成功，邮件ID: {email_message.id}")
        
    except Exception as e:
        print(f"❌ 发送密码重置邮件失败: {e}")
    finally:
        db.close()


async def main():
    """运行所有示例"""
    print("🚀 开始邮件系统示例演示...\n")
    
    examples = [
        ("发送简单邮件", example_send_simple_email),
        ("发送欢迎邮件", example_send_welcome_email),
        ("发送系统通知", example_send_notification),
        ("发送密码重置邮件", example_send_password_reset),
        ("批量发送邮件", example_send_batch_emails),
        # ("发送用户消息", example_send_user_message),  # 需要实际用户数据
    ]
    
    for name, func in examples:
        print(f"\n📧 {name}:")
        try:
            await func()
        except Exception as e:
            print(f"❌ {name}失败: {e}")
    
    print("\n✅ 邮件系统示例演示完成！")


if __name__ == "__main__":
    asyncio.run(main())